package com.jsh.erp.service.crk;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.KucunMapper;
import com.jsh.erp.datasource.mappers.ShipuMapper;
import com.jsh.erp.datasource.mappers.ShipuWeekMapper;
import com.jsh.erp.datasource.mappers.ShipuWeekMapperEx;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class ShipuWeekService {
    private Logger logger = LoggerFactory.getLogger(ShipuWeekService.class);

    @Resource
    private KucunMapper kucunMapper;
    @Resource
    private ShipuMapper shipuMapper;
    @Resource
    private ShipuWeekMapper shipuWeekMapper;
    @Resource
    private ShipuWeekMapperEx shipuWeekMapperEx;
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;
    @Resource
    private KucunService kucunService;
    @Resource
    private ShipuService shipuService;


    public Shipu getShipu(long id)throws Exception {
        Shipu result=null;
        try{
            result= shipuMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<Shipu> getShipuListByIds(String ids)throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        List<Shipu> list = new ArrayList<>();
        try{
            ShipuExample example = new ShipuExample();
            example.createCriteria().andIdIn(idList);
            list = shipuMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Shipu> getShipu()throws Exception {
        ShipuExample example = new ShipuExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Shipu> list=null;
        try{
            list= shipuMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<ShipuWeekCount> select(String startDate, int offset, int rows)throws Exception {
        List<ShipuWeekCount> list=null;
        try{
            list= shipuWeekMapperEx.selectByConditionShipu(startDate, offset, rows);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public Long countShipu(String startDate)throws Exception {
        Long result=null;
        try{
            result= shipuWeekMapperEx.countsByShipu(startDate);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertShipu(JSONObject obj, HttpServletRequest request)throws Exception {
        Shipu inOutItem = JSONObject.parseObject(obj.toJSONString(), Shipu.class);
        int result=0;
        try{
            inOutItem.setEnabled(true);
            result= shipuMapper.insertSelective(inOutItem);
            logService.insertLog("食谱管理",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(inOutItem.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateShipu(JSONObject obj, HttpServletRequest request)throws Exception {
        Shipu inOutItem = JSONObject.parseObject(obj.toJSONString(), Shipu.class);
        int result=0;
        try{
            result= shipuMapper.updateByPrimaryKeySelective(inOutItem);
            logService.insertLog("食谱管理",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(inOutItem.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteShipu(String days, HttpServletRequest request)throws Exception {
        shipuService.deleteDayDetail(days);
        return 1;
    }

    public int checkIsNameExist(Long id, String name)throws Exception {
        ShipuExample example = new ShipuExample();
        example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Shipu> list = null;
        try{
            list= shipuMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }

        return list==null?0:list.size();
    }

    public List<Shipu> findBySelect()throws Exception {
        ShipuExample example = new ShipuExample();
        example.createCriteria().andEnabledEqualTo(true)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("sort asc, id desc");
        List<Shipu> list = null;
        try{
            list= shipuMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchSetStatus(Boolean status, String ids)throws Exception {
        logService.insertLog("食谱管理",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ENABLED).toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        List<Long> inOutItemIds = StringUtil.strToLongList(ids);
        Shipu inOutItem = new Shipu();
        inOutItem.setEnabled(status);
        ShipuExample example = new ShipuExample();
        example.createCriteria().andIdIn(inOutItemIds);
        int result=0;
        try{
            result = shipuMapper.updateByExampleSelective(inOutItem, example);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void addDetail(String type, String info, String rows) throws Exception {
        ShipuWeekHead head = JSONObject.parseObject(info, ShipuWeekHead.class);

        if(type.equalsIgnoreCase("add")){
            List<ShipuWeek> existList = shipuWeekMapper.queryByStartDate(head.getStartDate());
            if(!CollectionUtils.isEmpty(existList)){
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE, "数据重复: ".concat(head.getStartDate()));
            }
        }else{
            shipuWeekMapper.deleteByStartDate(head.getStartDate());
        }

        List<ShipuWeekItem> items = JSONArray.parseArray(rows, ShipuWeekItem.class);
        if(head != null && StringUtils.isNotEmpty(head.getStartDate()) && !CollectionUtils.isEmpty(items)){
            List<ShipuWeek> ShipuWeekList = Lists.newArrayList();
            items.forEach(item->{
                ShipuWeek ShipuWeek = new ShipuWeek();
                ShipuWeek.setStartDate(head.getStartDate());
                ShipuWeek.setDescription(head.getDescription());
                ShipuWeek.setDay(item.getDay());
                ShipuWeek.setWeek(item.getWeek());
                ShipuWeek.setBreakfast(item.getBreakfast());
                ShipuWeek.setLunch(item.getLunch());
                ShipuWeek.setDinner(item.getDinner());
                ShipuWeek.setNight(item.getNight());
                ShipuWeek.setRemark(item.getRemark());
                ShipuWeekList.add(ShipuWeek);
            });
            shipuWeekMapper.batchInsert(ShipuWeekList);
        }
    }

    public List<ShipuWeek> getDetailList(String startDate)throws Exception {
        return shipuWeekMapper.queryByStartDate(startDate);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void deleteDetail(String day) throws Exception {
        shipuWeekMapper.deleteByStartDate(day);
    }
}
